#ifndef DOWNLOADTASKS_H
#define DOWNLOADTASKS_H

#include <QFile>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QObject>
#include <QTimer>

//todo 假如没动了，就发送错误信息，如果在下载，不管多慢，都继续下载
//QNetworkReply::ProxyTimeoutError
class DownloadTasks : public QObject
{
    Q_OBJECT
public:
    enum class DownloadStatus{
        DS_Start,
        DS_Loading,
        DS_Finished
    };
    Q_ENUM(DownloadStatus)
    explicit DownloadTasks(QObject *parent = nullptr);
    //static DownloadTasks* Get();                                            //单例没有使用，使用的是将其添加为成员对象
    void cancelDownload();
    DownloadStatus status() const;
    void setStatus(DownloadStatus newStatus);
    
private:
    QFile* openFileForWrite(const QString& fileName);  
private:
    int m_queueSize = 0;
    quint64 m_allPackageSize = 0;
    
    bool m_httpRequestAborted;
    QNetworkAccessManager m_qnam;
    QMap<QNetworkReply*,QFile*> m_downloadMap;
    QMap<QNetworkReply*,qreal> m_downloadSizeMap;

    DownloadStatus m_status;
    QTimer * m_timer_check = nullptr;
    qint64 m_front;
    qint64 m_tail = -1;
public slots:
    void startRequest();
    void postHttp(const QString & http,const QJsonObject &);
private slots:
    void onHttpFinished();
    void onHttpReadyRead();
    void onNetworkReplyProgress(qint64 bytesRead,qint64 totalBytes);
signals:
    void sigAppearError();
    void sigDownloadSche(QString);
    void postReply(const QString& http,QString result,int code);
    void sigTimerout(QNetworkReply::NetworkError);
};

#endif // DOWNLOADTASKS_H
/*
 *  网络下载类
 *  与调用类处于同一线程，都是由信号处理，不会阻塞线程
*/
